package com.eliansun.crawler.engine;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author xpq
 */
@Component
@Scope("singleton")
public class Task {

    private final int MAX_SZIE = 1;

    private ExecutorService taskpool;

    private Lock lock = new ReentrantLock();

    @Autowired
    private GetTaskForSpider getTaskForSpider;


    public void run(){
        initTask();
    }

    private void initTask(){
        if(taskpool == null || taskpool.isTerminated()){
            lock.lock();
            taskpool = Executors.newFixedThreadPool(MAX_SZIE);
            for (int i=0;i<MAX_SZIE;i++){
                taskpool.execute(getTaskForSpider);
            }
            taskpool.shutdown();
            lock.unlock();
        }
    }

}
